package com.lin.missyou.manager.rocketmq;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
public class ProducerSchedule {

    @Value("${rocketmq.producer.producer-group}")
    private String producerGroup;

    @Value("${rocketmq.namesrv-addr}")
    private String namesrvAddr;
    // rocketmq 的生产者
    private DefaultMQProducer defaultMQProducer;

//    执行顺序： A Construct--> B @Autowired --> @PostConstruct
    @PostConstruct
    public void setDefaultMQProducer() {
        if (defaultMQProducer == null) {
            //在类实例化后，创建defaultMQProducer对象
            this.defaultMQProducer = new DefaultMQProducer(producerGroup);
            // 设置rockemq的地址
            defaultMQProducer.setNamesrvAddr(namesrvAddr);
        }
        try {
            // 开启生成者
            defaultMQProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }


    public String send(String topic, String body) throws Exception {
        Message message = new Message(topic, body.getBytes());
        // messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        // 设置延时级别
        message.setDelayTimeLevel(3);
        // 发送消息
        SendResult sendResult = defaultMQProducer.send(message);

        System.out.println(sendResult.getMsgId());
        System.out.println(sendResult.getSendStatus());
        return sendResult.getMsgId();
    }
}
